package cn.arikeky.org.service.impl;


import cn.arikeky.basic.service.impl.BaseServiceImpl;
import cn.arikeky.org.domain.Department;
import cn.arikeky.org.mapper.DepartmentMapper;
import cn.arikeky.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;



    @Override
    public List<Department> batchTree() {
        List<Department> allDepts = departmentMapper.findAll();
        // stream 流
        Map<Long, Department> parentMap = allDepts.stream().collect(Collectors.toMap(Department::getId, e -> e));

        List<Department> result = new ArrayList<>();

        for (Department dept : allDepts){
            if (null == dept.getParentId()){
                result.add(dept);
            } else {
                Department parent = parentMap.get(dept.getParentId());
                if (null == parent){
                    break;
                }
                parent.getChildren().add(dept);
//                Long parentId = dept.getParentId();
//               for (Department parent : allDepts){
//                   if (parent.getId().equals(dept.getParentId())){
//                       parent.getChildren().add(dept);
//                       break;
//                   }
//               }
            }
        }
        return result;
    }
}
